package com.qilu.config;

import com.qilu.handler.LoginHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.annotation.WebFilter;

@Configuration
@WebFilter(filterName="WebMvcConfig",urlPatterns="/*")
public class WebMvcConfig implements WebMvcConfigurer {




	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*");
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		corsConfiguration.addExposedHeader("Authorization");
		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig());
		return new CorsFilter(source);
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				// 放行哪些原始域
				 .allowedOrigins("*")
				// 是否发送Cookie信息
				.allowCredentials(true)
				// 放行哪些原始域(请求方式)
				.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS", "HEAD")
				// 放行哪些原始域(头部信息)
				.allowedHeaders("*")
				// 暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
				// .exposedHeaders("Server","Content-Length", "Authorization", "Access-Token", "Access-Control-Allow-Origin","Access-Control-Allow-Credentials")
				.maxAge(3600);
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 自定义拦截器
		registry.addInterceptor(new LoginHandler())
				// 添加拦截路径
				.addPathPatterns("/**")
				// 不拦截路径
				.excludePathPatterns("/login")
				.excludePathPatterns("/swagger-resources/**","/webjars/**","/swagger-ui.html/**","/api","/api-docs","/api-docs/**","/doc.html/**");
	}

//	@Override
//	public void addResourceHandlers(ResourceHandlerRegistry registry) {
//		registry.addResourceHandler("/upload/**")
//				.addResourceLocations("file:" + FileUploadUtils.UPLOAD_PATH);
//	}
}
